package top.deepdesigner.config;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 处理跨域问题, shiro的拦截会导致跨域
 *
 * @author zhaojian
 */
public class AutchFilter extends FormAuthenticationFilter {

  /**
   * 确定是否应允许当前主体发出当前请求
   * 如果用户通过身份验证，默认实现返回true。也会回来
   *
   * @param request     请求
   * @param response    响应
   * @param mappedValue 映射值
   * @return boolean
   */
  @Override
  protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    String method = httpServletRequest.getMethod();

    //判断请求是否是预请求
    if (method.equalsIgnoreCase("options")) {
      //是就放行，给SpringMVC的处理器
      return true;
    }
    //否则放行给其他过滤器
    return super.isAccessAllowed(request, response, mappedValue);
  }


  /**
   * 在访问被拒绝
   * 认证失败触发，默认跳转到spring-shiro中配置的loginUrl路径
   *
   * @param request  请求
   * @param response 响应
   * @return boolean
   * @throws Exception 异常
   */
  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    return super.onAccessDenied(request, response);
  }

}


